package com.ruoyi.json;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @program: RuoYi
 * @description:
 * @author: yanghua
 * @create: 2021-07-01 12:24
 **/
public class Test {
    private static String path = "D:\\汽车部件数据训练\\Annotations";
    private static String path2 = "D:\\汽车部件数据训练\\xml";
    private static String path3 = "D:\\汽车部件数据训练\\Annotations";
    private static String path4 = "D:\\汽车部件数据训练\\newXml1";
    private static String path44 = "D:\\汽车部件数据训练\\newXml2";
    private static String path5 = "C:\\Users\\Hasee\\Desktop\\1111111.txt";
    private static String path6 = "D:\\汽车部件数据训练\\Images";
    private static String path7 = "D:\\汽车部件数据训练\\部分图片\\data_ori_train";

    public static void main(String[] args) throws IOException {
        //根据json文件生成xml文件
        //Test readJSON = new Test();
        //readJSON.readJson2();
        //xml中有多个<object>，属性name如果一样保持不变；如果不一样，比如不同个数为n，一个xml文件则生成n个
        //readJSON.newXml();
        //复制图片
        //readFile8();
        //复制xml
        readFile7();
        //读取文件夹中文件的名字
        //getFiles(path7);
    }
    public static void readFile8() throws IOException {

        try {
            Scanner in = new Scanner(new File(path5));
            while (in.hasNextLine()) {
                String[] str = in.nextLine().split("@");
                String imageName = str[0];
                int imageNum = Integer.valueOf(str[1].split("\\.")[0]);
                writerFile(imageName, imageNum);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }
    public static void readFile7() throws IOException {

        try {
            Scanner in = new Scanner(new File(path5));
            while (in.hasNextLine()) {
                String fn = in.next();

                String fileName = path44+"\\" + fn.split("\\.")[0]+".xml";//目的地址和图片名称

//        1、创建一个字节输入流FileInputStream对象，构造方法中绑定要读取的数据源
                FileInputStream fis = new FileInputStream(path4+"\\"+fn.split("\\.")[0]+".xml");

//        2、创建一个字节输出流FileOutputStream对象，构造方法中绑定写入的目的地；
                FileOutputStream os = new FileOutputStream(fileName);

                //        3、使用数组缓冲读取多个字节，写入多个字节，提高效率
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = fis.read(bytes)) != -1) {

//            4、使用字节输出流的方法wring，把读取出来的字节写入目的地
                    os.write(bytes, 0, len);

                }
                //        5、释放资源，先关闭写的
                os.close();
                fis.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }

    //复制图片
    public static void writerFile(String imageName,int fileNum) throws IOException {

        List<String> files = getFiles(path6);
        for (int j = 0; j <files.size() ; j++) {
            String name = new File(files.get(j)).getName();

            if (imageName.equals(name.split("\\.")[0])){

            for (int i = 0; i < fileNum; i++) {

                String fileName = path6+"\\" + imageName + "_new"+i + ".jpg";//目的地址和图片名称

//        1、创建一个字节输入流FileInputStream对象，构造方法中绑定要读取的数据源
                FileInputStream fis = new FileInputStream(path6+"\\"+name);

//        2、创建一个字节输出流FileOutputStream对象，构造方法中绑定写入的目的地；
                FileOutputStream os = new FileOutputStream(fileName);

                //        3、使用数组缓冲读取多个字节，写入多个字节，提高效率
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = fis.read(bytes)) != -1) {

//            4、使用字节输出流的方法wring，把读取出来的字节写入目的地
                    os.write(bytes, 0, len);

                }
                //        5、释放资源，先关闭写的
                os.close();
                fis.close();
            }
            new File(files.get(j)).delete();
            }
        }




    }

    //xml中有多个<object>，属性name如果一样保持不变；如果不一样，比如不同个数为n，一个xml文件则生成n个
    public void newXml() throws IOException {
        List<String> files = getFiles(path3);

        for (int i = 0; i < files.size(); i++) {
            Set<String> treeSet = new TreeSet<>();
            File file = new File(files.get(i));
            FeatureCollection featureCollection = new ObjectMapper().readValue(file, FeatureCollection.class);
            /**
             * 图片像素点
             */
            List<MyShapes> shapes = featureCollection.getShapes();
            //获取name属性，不重复
            for (int j = 0; j < shapes.size(); j++) {
                MyShapes sh = shapes.get(j);
                treeSet.add(sh.getLabel());
            }


            //判断treeSet集合的个数n，对oldxml重新生成n个newxml
            int k = 0;
            int size = treeSet.size();
            if (size > 1) {
                Iterator<String> iterator = treeSet.iterator();
                Set<String> names = new TreeSet<>();
                while (iterator.hasNext()) {
                    String next = iterator.next();

                    String str = "<annotation>\n";
                    //图片名称
                    String name = file.getName();
                    names.add(name.split("\\.")[0] + "@" + size + ".jpg");//原图片的名称
                    str += "\t<filename>" + name.split("\\.")[0] + "_new" + k + ".jpg" + "</filename>\n" +
                            "\t<source>\n" +
                            "\t\t<database>Unknown</database>\n" +
                            "\t</source>\n" +
                            "\t<size>\n";

                    // 图片高
                    String imageHeight = featureCollection.getImageHeight();
                    //宽
                    String imageWidth = featureCollection.getImageWidth();
                    str += "\t\t<width>" + imageWidth + "</width>\n" +
                            "\t\t<height>" + imageHeight + "</height>\n" +
                            "\t\t<depth>3</depth>\n" +
                            "\t</size>\n" +
                            "\t<segmented>0</segmented>\n";
                    /**
                     * 图片像素点
                     */
                    List<MyShapes> shapes2 = featureCollection.getShapes();
                    for (int j = 0; j < shapes2.size(); j++) {


                        MyShapes sh = shapes2.get(j);
                        //像素点问题名称
                        String label = sh.getLabel();
                        if (label.equals(next)) {
                            treeSet.add(label);
                            //像素点的xmin，ymin，xmax，ymax
                            String[][] points = sh.points;
                            String xmin = "0";
                            String ymin = "0";
                            String xmax = "0";
                            String ymax = "0";
                            if (points.length == 2) {
                                xmin = points[0][0];
                                ymin = points[0][1];

                                xmax = points[1][0];
                                ymax = points[1][1];
                            } else {
                                System.out.println();
                                xmin = points[0][0];
                                ymin = points[0][1];
                            }

                            str += "\t<object>\n" +
                                    "\t\t<name>" + label + "</name>\n" +
                                    "\t\t<pose>Unspecified</pose>\n" +
                                    "\t\t<truncated>0</truncated>\n" +
                                    "\t\t<difficult>0</difficult>\n" +
                                    "\t\t<bndbox>\n" +
                                    "\t\t\t<xmin>" + Math.round(Double.valueOf(xmin)) + "</xmin>\n" +
                                    "\t\t\t<ymin>" + Math.round(Double.valueOf(ymin)) + "</ymin>\n" +
                                    "\t\t\t<xmax>" + Math.round(Double.valueOf(xmax)) + "</xmax>\n" +
                                    "\t\t\t<ymax>" + Math.round(Double.valueOf(ymax)) + "</ymax>\n" +
                                    "\t\t</bndbox>\n" +
                                    "\t</object>\n";
                        }
                    }
                    str += "</annotation>\n";
                    //生成xml文件
                    String filePath = path4 + "\\" + name.split("\\.")[0] + "_new" + k + ".xml";
                    WriteStringToFile(filePath, str);
                    k++;
                }
                Iterator<String> it = names.iterator();
                while (it.hasNext()) {
                    System.out.println(it.next());
                }
            }


        }

    }

    //根据json文件生成xml文件
    public void readJson2() throws IOException {
        String strstr = "";
        Scanner in = new Scanner(new File(path5));
        while (in.hasNextLine()) {
            String[] str = in.nextLine().split("@");
            strstr += str[0] + ".json";

        }

        List<String> files = getFiles(path);
        Set<String> treeSet = new TreeSet<>();
        for (int i = 0; i < files.size(); i++) {


            File file = new File(files.get(i));
            FeatureCollection featureCollection = new ObjectMapper().readValue(file, FeatureCollection.class);
            //图片名称
            String name = file.getName();
            if (!strstr.contains(name)) {


                String str = "<annotation>\n";
                str += "\t<filename>" + name.split("\\.")[0] + ".jpg" + "</filename>\n" +
                        "\t<source>\n" +
                        "\t\t<database>Unknown</database>\n" +
                        "\t</source>\n" +
                        "\t<size>\n";
                // 图片高
                String imageHeight = featureCollection.getImageHeight();
                //宽
                String imageWidth = featureCollection.getImageWidth();
                str += "\t\t<width>" + imageWidth + "</width>\n" +
                        "\t\t<height>" + imageHeight + "</height>\n" +
                        "\t\t<depth>3</depth>\n" +
                        "\t</size>\n" +
                        "\t<segmented>0</segmented>\n";
                /**
                 * 图片像素点
                 */
                List<MyShapes> shapes = featureCollection.getShapes();
                for (int j = 0; j < shapes.size(); j++) {
                    MyShapes sh = shapes.get(j);
                    //像素点问题名称
                    String label = sh.getLabel();
                    treeSet.add(label);
                    //像素点的xmin，ymin，xmax，ymax
                    String[][] points = sh.points;
                    String xmin = "0";
                    String ymin = "0";
                    String xmax = "0";
                    String ymax = "0";
                    if (points.length == 2) {
                        xmin = points[0][0];
                        ymin = points[0][1];

                        xmax = points[1][0];
                        ymax = points[1][1];
                    } else {
                        System.out.println(name);
                        xmin = points[0][0];
                        ymin = points[0][1];
                    }

                    str += "\t<object>\n" +
                            "\t\t<name>" + label + "</name>\n" +
                            "\t\t<pose>Unspecified</pose>\n" +
                            "\t\t<truncated>0</truncated>\n" +
                            "\t\t<difficult>0</difficult>\n" +
                            "\t\t<bndbox>\n" +
                            "\t\t\t<xmin>" + Math.round(Double.valueOf(xmin)) + "</xmin>\n" +
                            "\t\t\t<ymin>" + Math.round(Double.valueOf(ymin)) + "</ymin>\n" +
                            "\t\t\t<xmax>" + Math.round(Double.valueOf(xmax)) + "</xmax>\n" +
                            "\t\t\t<ymax>" + Math.round(Double.valueOf(ymax)) + "</ymax>\n" +
                            "\t\t</bndbox>\n" +
                            "\t</object>\n";
                }
                str += "</annotation>\n";
                //生成xml文件
                String filePath = path4 + "\\" + name.split("\\.")[0] + ".xml";
                WriteStringToFile(filePath, str);
            }
        }

    }

    public void WriteStringToFile(String filePath, String s) {
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(s.getBytes());
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @Author：
     * @Description：获取某个目录下所有直接下级文件，不包括目录下的子目录的下的文件，所以不用递归获取
     * @Date：
     */
    public static List<String> getFiles(String path) {
        List<String> files = new ArrayList<String>();
        File file = new File(path);
        File[] tempList = file.listFiles();

        for (int i = 0; i < tempList.length; i++) {
            if (tempList[i].isFile()) {
                files.add(tempList[i].toString());
                //文件名，不包含路径
                System.out.println( tempList[i].getName());
            }
            if (tempList[i].isDirectory()) {
                //这里就不递归了，
            }
        }
        return files;
    }

}
